package com.tianhui.consignortwofei.mvp.ui.activity.carrier;

import android.graphics.Color;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;

import com.fgs.common.CommonFragment;
import com.fgs.common.CommonPresenter;
import com.fgs.common.CommonResponse;
import com.fgs.common.CommonView;
import com.fgs.common.entity.PictureInfo;
import com.fgs.common.entity.SelectItemInfo;
import com.fgs.common.entity.UploadPictureInfo;
import com.fgs.common.imageView.strategy.ImageLoader;
import com.fgs.common.other.RegionData;
import com.fgs.common.pictureSelector.SelectPicture;
import com.fgs.common.progress.ExceptionHandle;
import com.fgs.common.progress.ObserverResponseListener;
import com.fgs.common.uploadPicture.IUploadPicture;
import com.fgs.common.uploadPicture.UploadPicture;
import com.fgs.common.utils.ToastUtil;
import com.fgs.common.widget.SelectDialog;
import com.fgs.common.widget.itemView.ClickItemView;
import com.fgs.common.widget.itemView.InputItemView;
import com.luck.picture.lib.entity.LocalMedia;
import com.tianhui.consignortwofei.R;
import com.tianhui.consignortwofei.base.BaseActivity;
import com.tianhui.consignortwofei.constant.KeyValue;
import com.tianhui.consignortwofei.manager.EventBusManage;
import com.tianhui.consignortwofei.mvp.model.CarrierModel;
import com.tianhui.consignortwofei.mvp.model.DriverModel;
import com.tianhui.consignortwofei.mvp.model.enty.CarrierInfo;
import com.tianhui.consignortwofei.mvp.model.enty.DriverInfo;
import com.xuexiang.xui.widget.picker.widget.OptionsPickerView;
import com.xuexiang.xui.widget.picker.widget.builder.OptionsPickerBuilder;
import com.xuexiang.xui.widget.picker.widget.listener.OnOptionsSelectListener;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * @author fgs
 * @date 2021/5/22
 * @description
 **/
public class AddCarrierActivity extends BaseActivity {

    private static final int FRONT = 0;
    private static final int BACK = 1;

    @BindView(R.id.activity_add_carrier_leftImageView)
    protected ImageView idCardFrontImageView;
    @BindView(R.id.activity_add_carrier_rightImageView)
    protected ImageView idCardBackImageView;
    @BindView(R.id.activity_add_carrier_carrierNumberInputItemView)
    protected InputItemView carrierNumberInputItemView;
    @BindView(R.id.activity_add_carrier_carrierNameInputItemView)
    protected InputItemView carrierNameInputItemView;
    @BindView(R.id.activity_add_carrier_carrierTypeClickItemView)
    protected ClickItemView carrierTypeClickItemView;
    @BindView(R.id.activity_add_carrier_idCardNumberInputItemView)
    protected InputItemView idCardNumberInputItemView;
    @BindView(R.id.activity_add_carrier_contractsInputItemView)
    protected InputItemView contractsInputItemView;
    @BindView(R.id.activity_add_carrier_carrierPhoneInputItemView)
    protected InputItemView carrierPhoneInputItemView;
    @BindView(R.id.activity_add_carrier_addressClickItemView)
    protected ClickItemView addressClickItemView;

    protected DriverModel driverModel;
    protected CarrierInfo carrierInfo;
    protected CarrierModel carrierModel;
    protected OptionsPickerView mProvincePickerView;
    protected boolean mHasLoaded;

    protected SelectPicture mFrontSelectPicture;
    protected SelectPicture mBackSelectPicture;

    protected SelectDialog mCarrierTypeSelectDialog;


    @Override
    public int getLayoutId() {
        return R.layout.activity_add_carrier;
    }

    @Override
    public CommonPresenter createPresenter() {
        return null;
    }

    @Override
    public CommonView createView() {
        return null;
    }

    @Override
    public void init() {

        setTitle("添加承运商");
        mHasLoaded = RegionData.getInstance().loadProvinceData(RegionData.TYPE_NORMAL);

        driverModel = new DriverModel();
        carrierModel = new CarrierModel();

        Bundle bundle = getIntent().getExtras();
        if (bundle != null && !bundle.isEmpty()) {
            DriverInfo driverInfo = bundle.getParcelable(KeyValue.KEY_DRIVER_INFO);
            if (driverInfo != null) {
                requestDriverInfo(driverInfo);
            }
            carrierInfo = bundle.getParcelable(KeyValue.KEY_CARRIER_INFO);
            if (carrierInfo != null) {
                showCarrierInfo(carrierInfo);
            }
        }

        if (carrierInfo == null) {
            carrierInfo = new CarrierInfo();
        }


        mFrontSelectPicture = new SelectPicture();
        mFrontSelectPicture.setCrop(true);
        mBackSelectPicture = new SelectPicture();
        mBackSelectPicture.setCrop(true);

        initListener();

    }

    public void showCarrierInfo(CarrierInfo carrierInfo) {

        DriverInfo driverInfo = new DriverInfo();
        driverInfo.idcardtphoto = carrierInfo.idcardtphoto;
        driverInfo.idcardfphoto = carrierInfo.idcardfphoto;

        driverInfo.driverno = carrierInfo.carrierno;
        driverInfo.drivername = carrierInfo.carriername;
        driverInfo.driveridcard = carrierInfo.idcard;

        driverInfo.driverprovince = carrierInfo.carrierprovince;
        driverInfo.drivercity = carrierInfo.carriercity;
        driverInfo.drivercounty = carrierInfo.carriercounty;
        driverInfo.areacode = carrierInfo.areacode;

        showDriverInfo(driverInfo);
    }

    private void initListener() {
        idCardFrontImageView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mFrontSelectPicture.selectSinglePicture(AddCarrierActivity.this, new SelectPicture.OnSelectResultCallback() {
                    @Override
                    public void selectResultCallback(List<LocalMedia> selectList) {
                    }

                    @Override
                    public void selectResultPath(String path) {
                        requestUploadPicture(path, FRONT);
                    }

                    @Override
                    public void deletePictureCallback(List<LocalMedia> selectList, int position) {

                    }
                });
            }
        });
        idCardBackImageView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mBackSelectPicture.selectSinglePicture(AddCarrierActivity.this, new SelectPicture.OnSelectResultCallback() {
                    @Override
                    public void selectResultCallback(List<LocalMedia> selectList) {
                    }

                    @Override
                    public void selectResultPath(String path) {
                        requestUploadPicture(path, BACK);
                    }

                    @Override
                    public void deletePictureCallback(List<LocalMedia> selectList, int position) {

                    }
                });
            }
        });
    }

    private void requestUploadPicture(String path, int type) {

        UploadPictureInfo uploadPictureInfo = new UploadPictureInfo();
        uploadPictureInfo.pictureModule = "driver";
        uploadPictureInfo.picturePath = path;
        new UploadPicture(new IUploadPicture.UploadPictureCallback() {
            @Override
            public void onSuccess(UploadPictureInfo uploadPictureInfo, PictureInfo pictureInfo) {
                if (type == FRONT) {
                    loadImage(idCardFrontImageView, pictureInfo.id);
                    carrierInfo.idcardtphoto = pictureInfo.id;
                } else {
                    carrierInfo.idcardfphoto = pictureInfo.id;
                    loadImage(idCardBackImageView, pictureInfo.id);
                }

            }

            @Override
            public void onFailed(UploadPictureInfo uploadPictureInfo) {

            }
        }).uploadPicture(this, uploadPictureInfo);

    }

    private void requestDriverInfo(DriverInfo driverInfo) {
        if (driverInfo != null && !TextUtils.isEmpty(driverInfo.id)) {
            String driverId = driverInfo.id;
            Map<String, String> map = new HashMap<>();
            map.put("id", driverId);
            driverModel.driverInfoModel(this, map, true, this.bindLifecycle(), new ObserverResponseListener<CommonResponse<DriverInfo>>() {
                @Override
                public void onNext(CommonResponse<DriverInfo> commonResponse) {
                    if (commonResponse.getCode() == 20000) {
                        DriverInfo driverInfo = commonResponse.getData();
                        if (driverInfo != null) {
                            showDriverInfo(driverInfo);
                        }

                    } else {
                        ToastUtil.showShortToast(commonResponse.getMsg());
                    }

                }

                @Override
                public void onError(ExceptionHandle.ResponseThrowable e) {
                    ToastUtil.showShortToast(e.message);
                }
            });
        } else {
            showToast("获取司机信息失败");
        }
    }

    @Override
    public CommonFragment createFragment() {
        return null;
    }

    private void showDriverInfo(DriverInfo driverInfo) {

        loadImage(idCardFrontImageView, driverInfo.idcardtphoto);
        loadImage(idCardBackImageView, driverInfo.idcardfphoto);

        carrierNumberInputItemView.setContent(driverInfo.driverno);
        carrierNameInputItemView.setContent(driverInfo.drivername);
        idCardNumberInputItemView.setContent(driverInfo.driveridcard);
        addressClickItemView.setContent(driverInfo.driverprovince + " " + driverInfo.drivercity + " " + driverInfo.drivercounty);

        carrierInfo.carrierprovince = driverInfo.driverprovince;
        carrierInfo.carriercity = driverInfo.drivercity;
        carrierInfo.carriercounty = driverInfo.drivercounty;
        carrierInfo.areacode = driverInfo.areacode;

        carrierInfo.idcardtphoto = driverInfo.idcardtphoto;
        carrierInfo.idcardfphoto = driverInfo.idcardfphoto;

    }

    private void loadImage(ImageView imageView, String pictureId) {
        ImageLoader.init().loadImageWithId(imageView, pictureId);
    }

    @OnClick(R.id.activity_add_carrier_commitButton)
    public void commit() {
        String carrierName = carrierNameInputItemView.getContent();
        if (TextUtils.isEmpty(carrierName)) {
            showToast("请输入承运商名称");
            return;
        }
        carrierInfo.carriername = carrierName;

        String carrierType = carrierTypeClickItemView.getContent();
        if (TextUtils.isEmpty(carrierType)) {
            showToast("请选择承运商类型");
            return;
        }


        String idCardNumber = idCardNumberInputItemView.getContent();
        if (TextUtils.isEmpty(idCardNumber)) {
            showToast("请输入身份证号");
            return;
        }

        carrierInfo.idcard = idCardNumber;

        String carrierPhone = carrierPhoneInputItemView.getContent();
        if (TextUtils.isEmpty(carrierPhone)) {
            showToast("请输入联系人电话");
            return;
        }

        carrierInfo.carriertel = carrierPhone;

        String address = addressClickItemView.getContent();
        if (TextUtils.isEmpty(address)) {
            showToast("请选择注册地址");
            return;
        }

        String carrierContractsName = contractsInputItemView.getContent();
        carrierInfo.carrieruername = carrierContractsName;

        if (TextUtils.isEmpty(carrierInfo.id)) {
            carrierInfo.id = "";
        }
        carrierInfo.isaudit = 1;
        if (TextUtils.isEmpty(carrierInfo.istatus)) {
            carrierInfo.istatus = "1";
        }
        if (TextUtils.isEmpty(carrierInfo.carrierpassword)) {
            carrierInfo.carrierpassword = "123456";
        }
        if (TextUtils.isEmpty(carrierInfo.creditscore)) {
            carrierInfo.creditscore = "100";
        }
        requestAddCarrier(carrierInfo);
    }

    private void requestAddCarrier(CarrierInfo carrierInfo) {
        carrierModel.carrierAddModel(getContext(), carrierInfo, true, this.bindLifecycle(), new ObserverResponseListener<CommonResponse>() {
            @Override
            public void onNext(CommonResponse commonResponse) {
                if (commonResponse.getCode() == 20000) {
                    EventBusManage.refreshCarrierList();
                    finish();
                } else {
                    showToast(commonResponse.getMsg());
                }

            }

            @Override
            public void onError(ExceptionHandle.ResponseThrowable e) {
                showToast(e.message);
            }
        });
    }

    @OnClick(R.id.activity_add_carrier_addressClickItemView)
    public void region() {
        hideKeyboard();
        if (!mHasLoaded) {
            showToast("数据加载中...");
            return;
        }
        if (mProvincePickerView == null) {

            mProvincePickerView = new OptionsPickerBuilder(this, new OnOptionsSelectListener() {
                @Override
                public boolean onOptionsSelect(View v, int options1, int options2, int options3) {
                    //返回的分别是三个级别的选中位置
                    String province = RegionData.getInstance().getProvinceInfo(options1).name;
                    String city = RegionData.getInstance().getCityInfo(options1, options2).name;
                    String region = RegionData.getInstance().getAreaInfo(options1, options2, options3).name;

                    String regionCode = RegionData.getInstance().getAreaInfo(options1, options2, options3).code;

                    String tx = province + " " + city + " " + region;
                    addressClickItemView.setContent(tx);

                    carrierInfo.carrierprovince = province;
                    carrierInfo.carriercity = city;
                    carrierInfo.carriercounty = region;
                    carrierInfo.areacode = regionCode;


                    return false;
                }
            })

                    .setTitleText("地址选择")
                    .setDividerColor(Color.BLACK)
                    //切换选项时，还原到第一项
                    .isRestoreItem(true)
                    //设置选中项文字颜色
                    .setTextColorCenter(Color.BLACK)
                    .setContentTextSize(20)
                    .isDialog(false)
                    .setSelectOptions(RegionData.getInstance().getDefaultProvince(), RegionData.getInstance().getDefaultCity(), RegionData.getInstance().getDefaultArea())
                    .build();

            mProvincePickerView.setPicker(RegionData.getInstance().getProvinceItems(), RegionData.getInstance().getCityItems(), RegionData.getInstance().getAreaItems());//三级选择器
            mProvincePickerView.show();
        }
        mProvincePickerView.show();
    }

    @OnClick(R.id.activity_add_carrier_carrierTypeClickItemView)
    public void carrierType() {
        if (mCarrierTypeSelectDialog == null) {
            mCarrierTypeSelectDialog = new SelectDialog(getContext());
            mCarrierTypeSelectDialog.setTitle("承运商类型");
            mCarrierTypeSelectDialog.setList(getCarrierTypeList());
            mCarrierTypeSelectDialog.setOnSelectItemClickLister(new SelectDialog.OnSelectItemClickListener<SelectItemInfo>() {
                @Override
                public void onItemClick(SelectItemInfo item, int position) {
                    carrierTypeClickItemView.setContent(item.content);
                    carrierInfo.carriertype = item.value;
                }
            });

        }
        mCarrierTypeSelectDialog.show();
    }

    private List<SelectItemInfo> getCarrierTypeList() {
        List<SelectItemInfo> list = new ArrayList<>();
        SelectItemInfo info;
        info = new SelectItemInfo();
        info.content = "自营车";
        info.value = "0";
        list.add(info);

        info = new SelectItemInfo();
        info.content = "外协车";
        info.value = "1";
        list.add(info);

        info = new SelectItemInfo();
        info.content = "其他";
        info.value = "2";
        list.add(info);

        return list;
    }
}
